package ru.spb.nicetu.schoolproject.data;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;

import javax.swing.*;
import java.lang.reflect.Array;
import java.util.List;

/**
 * Created by dchernyshov on 16.04.15.
 */
public class ComboBoxData<TT> {

    private java.util.List<TT> comboList;
    private TT[] comboArray;

    private Session session;
    private HibernatePagination<TT> hibernatePagination;

    private Class<TT> clazz;

    public ComboBoxData() {}

    public ComboBoxData(Class<TT> clazz) {
        this.clazz = clazz;
        comboList = getComboList();
        comboArray = (TT[]) Array.newInstance(clazz, comboList.size());
        comboArray = comboList.toArray(comboArray);
    }

    public List<TT> getComboList() {
        session = HibernateUtil.getInstance().getSession();
        Criteria criteriaCount = session.createCriteria(clazz);
        criteriaCount.setProjection(Projections.rowCount());
        Long subjectCount = (Long) criteriaCount.uniqueResult();
        hibernatePagination = new HibernatePagination(clazz, subjectCount.intValue());
        return hibernatePagination.getPage(0);
    }

    public TT[] getComboArray() {
        return comboArray;
    }
}
